package look4ss.aplicativo;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.LinearLayout;
import look4ss.aplicativo.fragments.Nav;

public class ActivityPrincipal extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private static final String ID_ITEM_SELECIONADO = "ID_ITEM_SELECIONADO";
    private final Handler h = new Handler();
    private DrawerLayout Dl;
    private NavigationView nv;
    private int IdSelecionado;
    SharedPreferences sharp = null;
    private Toolbar toolb;
    public Menu menu;
    public static String idUsuario;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            startActivity(new Intent(ActivityPrincipal.this, Permissao.class));
            return;
        }
        startActivity(new Intent(this, Intro.class));
        setContentView(R.layout.activity_principal_lateral);
        sharp = getSharedPreferences("look4ss.aplicativo", MODE_PRIVATE);

        Dl = findViewById(R.id.layout_drawer);
        toolb = findViewById(R.id.barra1);
        setSupportActionBar(toolb);

        nv = findViewById(R.id.navegacao);
        assert nv != null;
        nv.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, Dl, toolb, R.string.ab, R.string.fe) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                super.onDrawerSlide(drawerView, 0);
            }
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, 0);
            }
        };
        Dl.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();

        SharedPreferences sharp = PreferenceManager.getDefaultSharedPreferences(this);
        IdSelecionado = nv.getMenu().getItem(sharp.getInt("view_padrao", 0)).getItemId();
        IdSelecionado = savedInstanceState == null ? IdSelecionado : savedInstanceState.getInt(ID_ITEM_SELECIONADO);
        nv.getMenu().findItem(IdSelecionado).setChecked(true);

        if (savedInstanceState == null) {
            h.removeCallbacksAndMessages(null);
            h.postDelayed(new Runnable() {
                @Override
                public void run() {
                    navegacao(IdSelecionado);
                }
            }, 250);

            boolean abrirDrawer = sharp.getBoolean("abre_drawer", false);

            if (abrirDrawer)
                Dl.openDrawer(GravityCompat.START);
            else
                Dl.closeDrawers();
        }
    }

    private void navegacao(final int itemId) {
        final View elevacao = findViewById(R.id.elevacaonavbars);
        Fragment fragmentoNavegacao = null;
        switch (itemId) {
            case R.id.opcao_inicio:
                setTitle(R.string.inicio);
                fragmentoNavegacao = new Nav();
                break;
            case R.id.editarContaBotao:
                startActivity(new Intent(this, ActivityEditarPerfil.class));
                break;
        }

        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dp(4));

        if (fragmentoNavegacao != null) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.setCustomAnimations(R.anim.animacao_fade_in, R.anim.animacao_fade_out);
            try {
                transaction.replace(R.id.conteudo, fragmentoNavegacao).commit();

                if (elevacao != null) {
                    params.topMargin = fragmentoNavegacao instanceof Nav ? dp(11) : 0;

                    Animation a = new Animation() {
                        @Override
                        protected void applyTransformation(float interpolatedTime, Transformation t) {
                            elevacao.setLayoutParams(params);
                        }
                    };
                    a.setDuration(150);
                    elevacao.startAnimation(a);
                }
            } catch (IllegalStateException ignored) {
            }
        }
    }

    public int dp(float valor) {
        float densidade = getApplicationContext().getResources().getDisplayMetrics().density;

        if (valor == 0) {
            return 0;
        }
        return (int) Math.ceil(densidade * valor);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem itemMenu) {
        itemMenu.setChecked(true);
        IdSelecionado = itemMenu.getItemId();
        h.removeCallbacksAndMessages(null);
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                navegacao(IdSelecionado);
            }
        }, 250);
        Dl.closeDrawers();
        return true;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(ID_ITEM_SELECIONADO, IdSelecionado);
    }
    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    public void onBackPressed() {
        if (Dl.isDrawerOpen(GravityCompat.START)) {
            Dl.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}